package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.PriorityDTO;
import business.PriorityManager;

/**
 * Servlet implementation class AddPriorityServlet
 */
@WebServlet("/AddPriority")
public class AddPriorityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PriorityManager pm = new PriorityManager();
		PriorityDTO priority = new PriorityDTO();
		System.out.println("in");
Map<String, String> errors = new HashMap<String, String>();
		
		String origin = request.getParameter("priorityName");
		
		if (origin.isEmpty()) {
			errors.put("origin", "Enter Priority Name");
		}else
		{
			errors.remove("origin");
		}
		
			if (errors.isEmpty()) {
				//priority.setPriorityID(Integer.parseInt(request.getParameter("priorityID")));
			   priority.setPriorityName(request.getParameter("priorityName"));
			   pm.insertPriority(priority);
			
			   ArrayList<PriorityDTO> data = pm.findAllPriorities();
				request.setAttribute("priorities", data);
				RequestDispatcher rd = request.getRequestDispatcher("LoadPriority.jsp");
				try {
			          rd.forward(request, response);
		       }       
				catch (ServletException e) {
			
			        e.printStackTrace();
		       } 
				catch (IOException e) {
			
			       e.printStackTrace();
		       }
	      }
			else {
				request.setAttribute("errors", errors);
		        request.getRequestDispatcher("/AddPriority.jsp").forward(request, response);
			
				}		
	}

}
